/*****************************************************************************
 *
 *                      HUSONG PROPRIETARY INFORMATION
 *
 *          The information contained herein is proprietary to HUSONG
 *           and shall not be reproduced or disclosed in whole or in part
 *                    or used for any design or manufacture
 *              without direct written authorization from HUSONG.
 *
 *            Copyright (c) 2015 by HUSONG.  All rights reserved.
 *
 *****************************************************************************/
package com.husong.common.shiro.hmac;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author maxmin
 *
 * @date 2015年11月9日 上午11:10:46
 */
public class DigestUtil {
	public static String digest(String key, String content) {
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            byte[] secretByte = key.getBytes("utf-8");
            byte[] dataBytes = content.getBytes("utf-8");

            SecretKey secret = new SecretKeySpec(secretByte, "HmacSHA1");
            mac.init(secret);

            byte[] doFinal = mac.doFinal(dataBytes);
            byte[] hexB = new Hex().encode(doFinal);
            return new String(hexB, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressWarnings("unchecked")
	public static String digest(String key, Map<String, ?> map) {
        StringBuilder s = new StringBuilder();
        List<String> list = new ArrayList<String>();
        for(Object values : map.values()) {
            if(values instanceof String[]) {
                for(String value : (String[])values) {
                    list.add(value);
                }
            } else if(values instanceof List) {
                for(String value : (List<String>)values) {
                    list.add(value);
                }
            } else {
                list.add((String) values);
            }
        }
        Collections.sort(list);
        for (String str : list) {
            s.append(str);
        }
        return digest(key, s.toString());
    }
    
    
    public static void main(String[] args) {
//		System.out.println(DigestUtil.d);
	}
}
